#! /usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020-11-05 23:50
# @Author : youngchaolin

# dumps和loads主要用户网络传输，但是也可以用在文件操作

# 字典
dic = {'name': 'messi', 'scores': 22, 'assists': 30}
import json

dic_str = json.dumps(dic, ensure_ascii=False)
print(dic_str, type(dic_str))
# 在反转回去
dic_1 = json.loads(dic_str)
print(dic_1, type(dic_1))

# 列表
li = [1, 2, 3]
li_str = json.dumps(li)
print(li_str, type(li_str))

# 反转回去
li_1 = json.loads(li_str)
print(li_1, type(li_1))

# 写入文件
with open('json.txt', mode='wt', encoding='utf-8') as f1:
    f1.write(dic_str)
# 反转回去
with open('json.txt', mode='rt', encoding='utf-8') as f1:
    st = json.loads(f1.read())
    print(st, type(st))

li = [1, 2, '梅西', {'name': 'messi', 'score': 100}]
# dump和load只能写入文件，只能写入一个数据结构
# with open('player',mode='w',encoding='utf-8') as f1:
#     json.dump(li,f1,ensure_ascii=False)

with open('player', mode='r', encoding='utf-8') as f1:
    ret = json.load(f1)
    print(ret, type(ret))

li1 = [1, 2, '梅西', {'name': 'messi', 'score': 100}]
li2 = [1, 2, 'C罗', {'name': 'ronald', 'score': 100}]
li3 = [1, 2, '亨利', {'name': 'herry', 'score': 80}]
# dump和load如果想多次读写数据，需要换行处理
# with open('players',mode='w',encoding='utf-8') as f1:
#     f1.write(json.dumps(li1,ensure_ascii=False)+'\n')
#     f1.write(json.dumps(li2,ensure_ascii=False)+'\n')
#     f1.write(json.dumps(li3,ensure_ascii=False)+'\n')

# 多次读取数据
with open('players', mode='r', encoding='utf-8') as f1:
    for line in f1:
        print(json.loads(line))
